import time
import random
import smtplib
import functools
from email.mime.text import MIMEText
from email.header import Header

from flask import session, request, redirect, url_for, flash
from flask_bcrypt import generate_password_hash

from config import EmailConfig, site_config_json


def sendCode(email):
    code = random.randint(100000, 999999)
    session[email] = code
    return sendEmail(email,
                     "邮箱验证码",
                     "您的邮箱验证码是: {}，请不要泄露给任何人！！".format(code))


def sendEmail(email, subject, content):
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header(site_config_json.get("name"), 'utf-8')
    message['To'] = Header(email, 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect(EmailConfig.EMAIL_HOST,
                        EmailConfig.EMAIL_PORT)
        smtpObj.login(EmailConfig.EMAIL_USER, EmailConfig.EMAIL_PASSWORD)
        smtpObj.sendmail(EmailConfig.EMAIL_USER, [email], message.as_string())
        return True
    except:
        return False


def login(info, resp, max_age=300):
    t = str(time.time())
    c = generate_password_hash(t).decode("utf-8") + info.get("password", "") + t
    session["_cookie"] = c
    resp.set_cookie("cookie", c)
    session["max_age"] = max_age
    session["_max_age"] = int(time.time()) + max_age
    # resp.set_cookie("cookie", info["password"], max_age=max_age)
    return True


def login_required(login_url, msg="需要先登录才能访问"):
    _login_url = "views.login"
    if not login_url:
        login_url = _login_url

    def wrap(fun):
        @functools.wraps(fun)
        def wrap_view(*args, **kwds):
            _cookie = session.get('_cookie')
            _max_age = session.get('_max_age')
            current_time = int(time.time())
            if (not _max_age) or (_max_age < current_time) or (not _cookie) or \
                    (_cookie != request.cookies.get("cookie", "")):
                flash(msg, "info")
                return redirect(url_for(login_url))
            else:
                session["_max_age"] = current_time + session["max_age"]
                return fun(*args, **kwds)
        return wrap_view

    if callable(login_url):
        fun = login_url
        login_url = _login_url
        return wrap(fun)
    return wrap


def logout(resp):
    session["_cookie"] = ""
    resp.delete_cookie("cookie")
    return True
